package cn.wen.yinxiu.system.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.wen.yinxiu.common.convention.errorcode.ErrorCode;
import cn.wen.yinxiu.common.convention.exception.ClientException;
import cn.wen.yinxiu.common.enums.DelEnum;
import cn.wen.yinxiu.common.enums.StatusEnum;
import cn.wen.yinxiu.common.toolkit.DateUtils;
import cn.wen.yinxiu.system.vo.ActivityListVO;
import cn.wen.yinxiu.system.vo.ActivityMonthVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.wen.yinxiu.common.toolkit.PageUtils;
import cn.wen.yinxiu.common.toolkit.Query;

import cn.wen.yinxiu.system.dao.ActivityDao;
import cn.wen.yinxiu.system.entity.ActivityEntity;
import cn.wen.yinxiu.system.service.ActivityService;


@Component
@Service("activityService")
public class ActivityServiceImpl extends ServiceImpl<ActivityDao, ActivityEntity> implements ActivityService {

    @Autowired
    private ActivityDao activityDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<ActivityEntity> page = this.page(
                new Query<ActivityEntity>().getPage(params),
                new QueryWrapper<ActivityEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<ActivityMonthVO> getActivityList(String yearMonth) {
        String[] yearMonthList = yearMonth.split("-");
        // 校验参数
        if (yearMonthList.length != 2 ||
                Integer.parseInt(yearMonthList[1]) > 12 || Integer.parseInt(yearMonthList[1]) < 1) {
            throw new ClientException(ErrorCode.CLIENT_PARAMS_ERROR);
        }
        // 数据库查询
        String monthEndTime = DateUtils.getOneMonthEndTime(Integer.parseInt(yearMonthList[0]), Integer.parseInt(yearMonthList[1]));
        String monthStartTime = DateUtils.getOneMonthStartTime(Integer.parseInt(yearMonthList[0]), Integer.parseInt(yearMonthList[1]));
        // 上面会出现某天不存在的情况 获取本月的全部天数
        List<String> monthList = DateUtils.getDayBetweenDates(monthStartTime, monthEndTime);
        List<ActivityMonthVO> resList = new ArrayList<>();
        for (String day : monthList) {
            ActivityMonthVO activityMonthVO = new ActivityMonthVO();
            activityMonthVO.setDay(day);
            List<ActivityListVO> worksList = activityDao.getActivityMonthList(day,
                    StatusEnum.NORMAL_USE.code(), DelEnum.NORMAL.code());
            activityMonthVO.setActivityList(worksList);
            resList.add(activityMonthVO);
        }
        return resList;
    }

}